package org.lilred.ui;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Manager;

public class CollapseableThemedField extends Manager implements FieldChangeListener {
	ClickableThemedField titleField;
	Manager contentManager;
	protected boolean collapsed = true;
	
	public CollapseableThemedField(ClickableThemedField titleField, Manager contentManager) {
		super(0);
		this.titleField = titleField;
		this.titleField.setChangeListener(this);
		this.contentManager = contentManager;
		add(titleField);
	}
	
	public void collapse() {
		if (collapsed) return;
		collapsed = true;
		titleField.getDefaultTheme().setBorderBottom(true);
		titleField.getFocusTheme().setBorderBottom(true);
		if (contentManager.getManager() == this) delete(contentManager);
	}
	
	public void expand() {
		if (!collapsed) return;
		collapsed = false;
		titleField.getDefaultTheme().setBorderBottom(false);
		titleField.getFocusTheme().setBorderBottom(false);
		if (contentManager.getManager() != this) add(contentManager);
	}

	protected void sublayout(int width, int height) {
		int offset = 0;
		layoutChild(titleField, width, titleField.getPreferredHeight());
		setPositionChild(titleField, 0, 0);
		offset += titleField.getHeight();
		if (!collapsed) {
			layoutChild(contentManager, width, height - titleField.getPreferredHeight());
			setPositionChild(contentManager, 0, offset);
			offset += contentManager.getHeight();
		}
		setExtent(width, offset);
	}
	
	public int getPreferredHeight() {
		if (collapsed) return titleField.getPreferredHeight();
		else return titleField.getPreferredHeight() + contentManager.getPreferredHeight();
	}
	
	public int getPreferredWidth() {
		return Math.max(titleField.getPreferredWidth(), contentManager.getPreferredWidth());
	}
	
	public boolean isCollapsed() { return collapsed; }

	/**
	 * Toggles the state of the collapseable field - either expanded or collapsed. 
	 */
	public void fieldChanged(Field field, int context) {
		if (field == titleField) {
			if (collapsed) expand();
			else collapse();
		}
		fieldChangeNotify(0);
	}
}
